package com.atjava.webspider.gui.task;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.commons.lang.StringUtils;

import com.atjava.jox.io.JOXWriter;
import com.atjava.webspider.consts.Const;
import com.atjava.webspider.gui.SpiderMainGui;
import com.atjava.webspider.gui.output.NewOutputGui;
import com.atjava.webspider.gui.table.DefaultTable;
import com.atjava.webspider.gui.table.DefaultTableModel;
import com.atjava.webspider.logic.ConfigLogic;
import com.atjava.webspider.model.DefaultResource;
import com.atjava.webspider.model.Resource;
import com.atjava.webspider.model.Site;
import com.atjava.webspider.model.Task;
import com.atjava.webspider.services.TableService;
import com.atjava.webspider.util.DateUtil;
import com.atjava.webspider.util.DialogUtil;
import com.atjava.webspider.util.TableUtil;

public class NewTaskGui extends JDialog {

	private static final long serialVersionUID = 1L;
	public static final String [] SCOPE_COMBOBOX = new String[]{"全文","变量"};
	private JPanel jContentPane = null;
	
	private JTabbedPane jTabbedPaneMain = null;
	private JPanel jPanelBasic = null;
	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel4 = null;
	private JTextField jTextFieldTskName = null;
	private JTextField jTextFieldTskURL = null;
	private JTextField jTextFieldTskDepth = null;
	private JTextField jTextFieldSavePath = null;
	
	private JPanel jPanelOutputSub = null;
	private JScrollPane jScrollPaneOutput = null;
	private JTable jTableOutput = null;
	private JButton jButtonOutput = null;
	private JButton jButtonOutputDel = null;
	private JButton jButtonBrowser = null;
	private JScrollPane jScrollPaneUrlRegexp = null;
	private JButton jButtonDone = null;
	private JPanel jPanelUrlRegexp = null;
	private JTable jTableResource = null;
	//private JButton jButtonDelResource = null;
	private Task task;
	private DefaultTableModel outputModel;
	private DefaultTableModel varModel;
	private DefaultTableModel resourceModel;
	private JButton jButtonOutputView = null;
	private JLabel jLabel3 = null;
	private JComboBox jComboBoxSite = null;
	/**
	 * @param owner
	 */
	public NewTaskGui(Frame owner,boolean modal) {
		this(owner,modal,new Task());
	}
	
	public NewTaskGui(Frame owner,boolean modal,Task task) {
		super(owner,modal);
		this.task = task;
		initialize();
		setTextValue();
	}
	
	private void setTextValue(){
		if(task == null)
			return ;
		try {

			if(StringUtils.isNotBlank(task.getName()))
				jTextFieldTskName.setText(task.getName());
			
			if(StringUtils.isNotBlank(task.getUrl()))
				jTextFieldTskURL.setText(task.getUrl());
			
			if(StringUtils.isNotBlank(task.getSavePath()))
				jTextFieldSavePath.setText(task.getSavePath());
			
			if(task.getMaxDepth() != 0)
				jTextFieldTskDepth.setText(String.valueOf(task.getMaxDepth()));
			
			if(StringUtils.isNotBlank(task.getSite()))
				jComboBoxSite.setSelectedItem(task.getSite());
			
			if(task.getResources() != null){
				DefaultTableModel dtm = (DefaultTableModel)jTableResource.getModel();
				TableService serv = TableService.getInstance();
				for (int i = 0; i < task.getResources().size(); i++) {
					Resource r = task.getResources().get(i);
					dtm.updateData(i, serv.getResRow(r));
				}
			}
			
			if(task.getOutputs() != null){
				DefaultTableModel dtm = (DefaultTableModel)jTableOutput.getModel();
				TableService serv = TableService.getInstance();
				dtm.updateAllData(serv.getOutputTable(task.getOutputs()));
				if(dtm.getRowCount() > 0)
					jTableOutput.setRowSelectionInterval(0, 0);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			DialogUtil.showError(this, "加载任务失败！");
		}
	}
	
	public DefaultTableModel getOutputModel(){
		return this.outputModel;
	}
	
	public DefaultTableModel getVarModel(){
		return this.varModel;
	}
	
	public DefaultTableModel getResourceModel(){
		return this.resourceModel;
	}
	
	public Task getTask(){
		return this.task;
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(705, 556);
		this.setResizable(false);
		this.setTitle("新建任务");
		this.setContentPane(getJContentPane());
		this.setLocationRelativeTo(getOwner());
		this.setModal(true);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJTabbedPaneMain(), null);
			jContentPane.add(getJButtonDone(), null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jTabbedPaneMain	
	 * 	
	 * @return javax.swing.JTabbedPane	
	 */
	private JTabbedPane getJTabbedPaneMain() {
		if (jTabbedPaneMain == null) {
			jTabbedPaneMain = new JTabbedPane();
			jTabbedPaneMain.setBounds(new Rectangle(0, 0, 700, 495));
			jTabbedPaneMain.addTab("基本信息", null, getJPanelBasic(), null);
			if(task.getId() != null){
			}
		}
		return jTabbedPaneMain;
	}

	/**
	 * This method initializes jPanelBasic	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelBasic() {
		if (jPanelBasic == null) {
			jLabel3 = new JLabel();
			jLabel3.setBounds(new Rectangle(415, 5, 65, 25));
			jLabel3.setText("采集站点：");
			jPanelBasic = new JPanel();
			jPanelBasic.setLayout(null);
			jLabel4 = new JLabel();
			jLabel4.setText("保存路径：");
			jLabel4.setSize(new Dimension(65, 25));
			jLabel4.setLocation(new Point(5, 75));
			jLabel2 = new JLabel();
			jLabel2.setText("最大深度：");
			jLabel2.setBounds(new Rectangle(547, 75, 65, 25));
			jLabel1 = new JLabel();
			jLabel1.setText("采集地址：");
			jLabel1.setSize(new Dimension(65, 25));
			jLabel1.setLocation(new Point(5, 40));
			jLabel = new JLabel();
			jLabel.setText("任务名称：");
			jLabel.setSize(new Dimension(65, 25));
			jLabel.setLocation(new Point(5, 5));
			jPanelBasic.add(jLabel1, null);
			jPanelBasic.add(jLabel2, null);
			jPanelBasic.add(getJTextFieldTskName(), null);
			jPanelBasic.add(getJTextFieldTskURL(), null);
			jPanelBasic.add(getJTextFieldTskDepth(), null);
			jPanelBasic.add(getJTextFieldSavePath(), null);
			jPanelBasic.add(jLabel4, null);
			jPanelBasic.add(jLabel, null);
			jPanelBasic.add(getJButtonBrowser(), null);
			jPanelBasic.add(getJPanelUrlRegexp(), null);
			jPanelBasic.add(getJPanelOutputSub(), null);
			jPanelBasic.add(jLabel3, null);
			jPanelBasic.add(getJComboBoxSite(), null);
		}
		return jPanelBasic;
	}

	/**
	 * This method initializes jTextFieldTskName	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldTskName() {
		if (jTextFieldTskName == null) {
			jTextFieldTskName = new JTextField();
			jTextFieldTskName.setBounds(new Rectangle(75, 5, 330, 25));
			jTextFieldTskName.setForeground(Color.black);
		}
		return jTextFieldTskName;
	}

	/**
	 * This method initializes jTextFieldTskURL	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldTskURL() {
		if (jTextFieldTskURL == null) {
			jTextFieldTskURL = new JTextField();
			jTextFieldTskURL.setBounds(new Rectangle(75, 40, 610, 25));
			jTextFieldTskURL.setForeground(Color.black);
		}
		return jTextFieldTskURL;
	}

	/**
	 * This method initializes jTextFieldTskDepth	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldTskDepth() {
		if (jTextFieldTskDepth == null) {
			jTextFieldTskDepth = new JTextField();
			jTextFieldTskDepth.setBounds(new Rectangle(611, 75, 73, 25));
			jTextFieldTskDepth.setForeground(Color.black);
			jTextFieldTskDepth.setText("3");
		}
		return jTextFieldTskDepth;
	}

	/**
	 * This method initializes jTextFieldSavePath	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextFieldSavePath() {
		if (jTextFieldSavePath == null) {
			jTextFieldSavePath = new JTextField();
			jTextFieldSavePath.setBounds(new Rectangle(75, 75, 406, 25));
			jTextFieldSavePath.setForeground(Color.black);
		}
		return jTextFieldSavePath;
	}

	/**
	 * This method initializes jPanelOutputSub	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelOutputSub() {
		if (jPanelOutputSub == null) {
			jPanelOutputSub = new JPanel();
			jPanelOutputSub.setLayout(null);
			jPanelOutputSub.setBounds(new Rectangle(1, 285, 692, 215));
			jPanelOutputSub.setBorder(BorderFactory.createTitledBorder(null, " 页面列表 "));
			jPanelOutputSub.add(getJScrollPaneOutput(), null);
			jPanelOutputSub.add(getJButtonOutput(), null);
			jPanelOutputSub.add(getJButtonOutputDel(), null);
			jPanelOutputSub.add(getJButtonOutputView(), null);
		}
		return jPanelOutputSub;
	}

	/**
	 * This method initializes jScrollPaneOutput	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPaneOutput() {
		if (jScrollPaneOutput == null) {
			jScrollPaneOutput = new JScrollPane();
			jScrollPaneOutput.setBounds(new Rectangle(8, 20, 676, 126));
			jScrollPaneOutput.setViewportView(getJTableOutput());
		}
		return jScrollPaneOutput;
	}

	/**
	 * This method initializes jTableOutput	
	 * 	
	 * @return javax.swing.JTable	
	 */
	public JTable getJTableOutput() {
		if (jTableOutput == null) {
			String [] colums = {"输出名称","输出路径","输出方式","页面规则"};
			outputModel = new DefaultTableModel(colums);
			jTableOutput = new DefaultTable(outputModel);
			jTableOutput.setRequestFocusEnabled(false);
			//调整大小
			TableUtil.fitTableColumns(jTableOutput,new int[]{40,40,150,206});
			jTableOutput.setRowHeight(25);
			TableUtil.setTableAlign(jTableOutput, JLabel.CENTER);
			jTableOutput.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			jTableOutput.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
				public void valueChanged(ListSelectionEvent evt) {
					/*int index = jTableOutput.getSelectedRow();
					if((index >= 0 && (index != outputIndex || outputIndex == -1))){
						try {
							outputIndex = index;
							Output out = task.getOutputs().get(index);
							TableService tabService = TableService.getInstance();
							List<String []> vars = tabService.getVarTable(out.getVariables());
							varModel.updateAllData(vars);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}*/
				}
			});
		}
		return jTableOutput;
	}

	/**
	 * This method initializes jButtonOutput	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutput() {
		if (jButtonOutput == null) {
			jButtonOutput = new JButton();
			jButtonOutput.setBounds(new Rectangle(397, 152, 90, 25));
			jButtonOutput.setText("新建页面");
			jButtonOutput.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					String site = (String)jComboBoxSite.getSelectedItem();
					if(StringUtils.isBlank(site)){
						DialogUtil.showWarning(NewTaskGui.this, "请选择所属采集站点！");
					}else{
						NewOutputGui newOutput = new NewOutputGui(NewTaskGui.this,true);
						newOutput.setVisible(true);
					}
				}
			});
		}
		return jButtonOutput;
	}
	
	/**
	 * This method initializes jButtonOutputDel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutputDel() {
		if (jButtonOutputDel == null) {
			jButtonOutputDel = new JButton();
			jButtonOutputDel.setBounds(new Rectangle(595, 152, 90, 25));
			jButtonOutputDel.setText("删除页面");
			jButtonOutputDel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = outputModel.getRowCount();
					int n = jTableOutput.getSelectedRow();
					if(rows > 0 && n >= 0){
						task.getOutputs().remove(n);
						outputModel.removeData(n);
						varModel.removeAllData();
					}
				}
			});
		}
		return jButtonOutputDel;
	}

	/**
	 * This method initializes jButtonBrowser	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonBrowser() {
		if (jButtonBrowser == null) {
			jButtonBrowser = new JButton();
			jButtonBrowser.setBounds(new Rectangle(486, 75, 50, 25));
			jButtonBrowser.setMargin(new Insets(2, 5, 2, 5));
			jButtonBrowser.setText("浏览");
			jButtonBrowser.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					String defPath = NewTaskGui.this.jTextFieldSavePath.getText();
					File selectDir;
					if(StringUtils.isNotBlank(defPath)){
						selectDir = new File(defPath).getParentFile();
					}else{
						selectDir = new File(Const.APP_PATH);
					}
					JFileChooser jc = new JFileChooser(selectDir);
					jc.setBackground(Color.WHITE);
					jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					jc.showOpenDialog(NewTaskGui.this);
					File f = jc.getSelectedFile();
					if( f == null )return ;
					NewTaskGui.this.jTextFieldSavePath.setText(f.getAbsolutePath());
				}
			});
		}
		return jButtonBrowser;
	}
	
	/**
	 * This method initializes jPanelPages	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelUrlRegexp() {
		if (jPanelUrlRegexp == null) {
			jPanelUrlRegexp = new JPanel();
			jPanelUrlRegexp.setLayout(null);
			jPanelUrlRegexp.setBounds(new Rectangle(1, 105, 692, 180));
			jPanelUrlRegexp.setBorder(BorderFactory.createTitledBorder(null, " 采集资源 "));
			jPanelUrlRegexp.add(getJScrollPaneUrlRegexp(), null);
		}
		return jPanelUrlRegexp;
	}

	/**
	 * This method initializes jScrollPanePages
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JScrollPane getJScrollPaneUrlRegexp() {
		if (jScrollPaneUrlRegexp == null) {
			jScrollPaneUrlRegexp = new JScrollPane();
			jScrollPaneUrlRegexp.setBounds(new Rectangle(8, 20, 676, 153));
			jScrollPaneUrlRegexp.setViewportView(getJTableResource());
		}
		return jScrollPaneUrlRegexp;
	}

	/**
	 * This method initializes jButtonDone	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonDone() {
		if (jButtonDone == null) {
			jButtonDone = new JButton();
			jButtonDone.setText("完成");
			jButtonDone.setBounds(new Rectangle(636, 497, 60, 26));
			jButtonDone.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					
					SpiderMainGui mainGui = SpiderMainGui.getInstance();
					File dir = mainGui.getJTree().getSelectFile();
					
					Task tsk = NewTaskGui.this.task;
					try {
						//任务基本信息
						tsk.setState(Const.TASK_STATE_SAVED);
						tsk.setSite
						(String.valueOf(NewTaskGui.this.jComboBoxSite.getSelectedItem()));
						tsk.setName(NewTaskGui.this.jTextFieldTskName.getText());
						tsk.setUrl(NewTaskGui.this.jTextFieldTskURL.getText());
						tsk.setSavePath(NewTaskGui.this.jTextFieldSavePath.getText());
						tsk.setMaxDepth(Integer.parseInt(NewTaskGui.this.jTextFieldTskDepth.getText()));
						//资源信息
						tsk.setResources(new ArrayList<Resource>());
						for (int i = 0; i < resourceModel.getRowCount(); i++) {
							String name = (String)resourceModel.getValueAt(i, 0);
							String path = (String)resourceModel.getValueAt(i, 1);
							String scp = (String)resourceModel.getValueAt(i, 2);
							if(StringUtils.isBlank(name))
								continue;
							Resource res = new Resource();
							res.setName(name);
							res.setPath(path);
							int scope = scp == NewTaskGui.SCOPE_COMBOBOX[0] ? 0 : 1;
							res.setScope(scope);
							tsk.getResources().add(res);
						}
						
						JOXWriter writer = new JOXWriter();
						File tskFile = null;
						if(StringUtils.isBlank(tsk.getId())){
							
							TableService tabService = TableService.getInstance();
							mainGui.getTaskModel().addData(tabService.getTaskRow(tsk));
							if(null == mainGui.getTaskMap().get(dir.getAbsolutePath())){
								mainGui.getTaskMap().put(dir.getAbsolutePath(), new ArrayList<Task>());
							}
							mainGui.getTaskMap().get(dir.getAbsolutePath()).add(tsk);
							//新建任务
							tskFile = new File(dir,"task-" + DateUtil.currentDateTime() + ".xml");
							tsk.setId(tskFile.getAbsolutePath());
						}else{
							//更新task列表
							tskFile = new File(tsk.getId());
						}
						writer.writeXml(tskFile, task);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					NewTaskGui.this.setVisible(false);
				}
			});
			
		}
		return jButtonDone;
	}

	/**
	 * This method initializes jTableResource	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableResource() {
		if (jTableResource == null) {
			String [] colums = {"资源名称","保存路径","采集范围"};
			List<DefaultResource> resources = ConfigLogic.getAppConfig().getResources();
			String [] resNames = new String[resources.size()+1];
			for (int i = 0; i < resources.size(); i++) {
				resNames[i+1] = resources.get(i).getName();
			}
			resNames[0] = " ";
			JComboBox jcbRes = new JComboBox(resNames);
			JComboBox jcbScope = new JComboBox(new String[]{"全文","变量"});
			
			resourceModel = new DefaultTableModel(colums,resources.size(),"");
			resourceModel.setEditable(true);
			jTableResource = new JTable(resourceModel);
			jTableResource.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(jcbRes));
			jTableResource.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(jcbScope));
			jTableResource.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			jTableResource.setRowHeight(25);
			TableUtil.setTableAlign(jTableResource, JLabel.CENTER);
		}
		return jTableResource;
	}

	/**
	 * This method initializes jButtonOutputView	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonOutputView() {
		if (jButtonOutputView == null) {
			jButtonOutputView = new JButton();
			jButtonOutputView.setBounds(new Rectangle(496, 152, 90, 25));
			jButtonOutputView.setText("查看页面");
			jButtonOutputView.addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int rows = outputModel.getRowCount();
					int n = jTableOutput.getSelectedRow();
					if(rows > 0 && n >= 0){
						NewOutputGui newOutput = new NewOutputGui
						(NewTaskGui.this,true,task.getOutputs().get(n));
						newOutput.setVisible(true);
					}
				}
			});
		}
		return jButtonOutputView;
	}

	/**
	 * This method initializes jComboBoxSite	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	public JComboBox getJComboBoxSite() {
		if (jComboBoxSite == null) {
			List<Site> sites = ConfigLogic.getSiteConfig().getSites();
			String [] sitesnm = new String [sites.size()+1];
			sitesnm[0] = "";
			for (int i = 1; i < sitesnm.length; i++) {
				sitesnm[i] = sites.get(i-1).getName();
			}
			jComboBoxSite = new JComboBox(sitesnm);
			jComboBoxSite.setBounds(new Rectangle(484, 5, 200, 25));
		}
		return jComboBoxSite;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
